﻿using System;
using System.Windows.Forms;

namespace AiFrame.InterfaceLib.MVVM
{
    /// <summary>
    /// Specifies nullable datetime bindings.
    /// </summary>
    public class NullableDateTimeBinding : Binding
    {
        public NullableDateTimeBinding(string propertyName, object dataSource, string dataMember, bool formattingEnabled, DataSourceUpdateMode dataSourceUpdateMode)
            : base(propertyName, dataSource, dataMember, formattingEnabled, dataSourceUpdateMode)
        {
        }

        protected override void OnFormat(ConvertEventArgs cevent)
        {
            DateTime? dt = cevent.Value as DateTime?;
            if (dt == null)
                return;

            cevent.Value = dt.Value.ToShortDateString();
        }

        protected override void OnParse(ConvertEventArgs cevent)
        {
            string text = cevent.Value as string;

            if (text == null)
                return;

            DateTime dt;

            if (DateTime.TryParse(text, out dt))
                cevent.Value = dt;
            else
                cevent.Value = null;
        }
    }
}
